package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.model.behavior.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.user.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        Long articleId = dto.getArticleId();//文章id
        Integer authorId = dto.getAuthorId();//文章作者id
        Short operation = dto.getOperation();//0关注  1取消

        //检查用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Integer userId = user.getId();
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //操作redis进行添加或删除
        if (1 == operation) {//取消关注
            //向自己的关注列表删除数据
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId.toString(), authorId);
            //向文章作者的粉丝列表删除数据
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId.toString(), userId);
        }

        if (0 == operation) {//关注
//            //先查看是否已经关注过了
//            cacheService.get()
            long currentTime = System.currentTimeMillis();//时间戳
            //向自己的关注列表添加数据：1.集合key  2.写入的数据   3.score
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId.toString(), authorId.toString(), currentTime);
            //向文章作者的粉丝列表添加数据
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId.toString(), userId.toString(), currentTime);

        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
